<?php

class BusinessDistrictForm extends HasManyForm {
	
	public function render() {
		$body = '';
		foreach(array_keys($this->model->{$this->relationName}) as $one) {
			$removeJs = '$("#attr_'.$one.'").remove()';
			$body .= 
			"<tr id='attr_{$one}'>".$this->renderHiddenRow($one)."
				<td><input onclick='{$removeJs}' type='button' value='   删除   ' class='pn'/></td>
			</tr>";
		}
		
		$foot = 
		'<tr id="item-content">'.$this->renderRow('{attrId}')."
			<td><input type='button' value='   添加   ' class='pn pnc btn-add-item'/></td>
		</tr>".
		'<tr id="item-template" style="display:none">'.$this->renderHiddenRow('{attrId}')."
			<td><input type='button' value='   添加   ' class='pn pnc btn-add-item'/></td>
		</tr>"
		;
		$className = get_class($this->model);
		$foot = str_replace($className, "_prefix_{$className}", $foot);
		
		$head = '';
		foreach($this->fields as $name=>$field) {
			$head .= '<th>'.$this->activeForm->labelEx($this->model, $name).'</th>';
		}
		$head .= '<th>操作</th>';
		
$template = <<<EOD
<table class='info mgb10' width=100% id='item-container'>
	<thead>{$head}</thead>
	<tbody id='item-container'>{$body}{$foot}</tbody>
</table>
EOD;

		echo $template;
		Yii::app()->clientScript->registerScript('hmf'.mktime(), $this->registerScript(), CClientScript::POS_END);
	}
	
	public function renderHiddenRow($attrId) {
		$rowTemplate = '';
		$model = $this->model;
		$form = $this->activeForm;
		foreach($this->fields as $name=>$field) {
			if(!$field->getIsVisible()) continue;
			$label = $model->getAttributeLabel($name);
			$attribute = str_replace('..', ".{$attrId}.", $name);
			$rowTemplate .= '<td class="vtop"><label>'.$this->label($model, $attribute).'</label>'.$form->hiddenField($model, $attribute).'</td>';
		}
		return $rowTemplate;
	}
	
	public function label($model, $attribute) {
		$model = CommonDistrict::model()->findByPk(CHtml::value($model, $attribute));
		$label = '';
		if (is_object($model)) {
			foreach ($model->getAncestors() as $one) {
				$label .= ' '.$one->name;
			}
		}
		return $label;
	}
	
	
	public function registerScript() {
$js = <<<EOD
$('.btn-add-item').click(function() {
	var e = $('#item-template').clone();
	var selectVal = '';
	var hiddenVal = '';
	$('#item-content select').each(function() {
		hiddenVal = $(this).find(':checked').val() == '' ? hiddenVal : $(this).find(':checked').val();
		selectVal += $(this).find(':checked').text() == '请选择' ? '' : ' '+$(this).find(':checked').text();
	});
	e.find('label').html(selectVal);
	e.find(':hidden').val(hiddenVal);
	e.show();
	id = 'N-'+new Date().getTime();
	e.find('.btn-add-item')
		.removeClass('btn-add-item')
		.removeClass('pnc')
		.val('   删除   ')
		.attr('onclick', "$('#attr_{attrId}').remove()");
	html = '<tr id="attr_{attrId}">'+e.html()+"</tr>";
	html = html.replace(/\{attrId\}/g, id);
	html = html.replace(/_prefix_/g, '');
	$(html).insertBefore($('#item-template'));
});
EOD;
	
		return $js;
	}
	

}

?>